package org.advanced.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author John.zhang
 * @version Id: ServerSockets, v 1.0 2020/12/14 15:42 ZhiYong Exp $
 */
public class ServerSockets {

    /**
     * 启动一个服务端
     *
     * @param args
     */
    public static void main(String[] args) {
        final int DEFAULT_PORT = 8082;
        ServerSocket serverSocket = null;
        try {
            //绑定一个监听端口
            serverSocket = new ServerSocket(DEFAULT_PORT);
            ExecutorService executorService = Executors.newFixedThreadPool(5);
            while (true){
                //等待客户端链接，连接阻塞操作
                Socket socket = serverSocket.accept();
                //异步处理方式
                executorService.submit(new ServerSocketThread(socket));
            }

            /*System.out.println("客户端" + socket.getPort() + "已经连接");
            //socket.getInputStream()这里来自于网络的IO ，相当于来自磁盘的new FileInputStream("")
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line = bufferedReader.readLine();
            System.out.println("收到客户端信息"+line);
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bufferedWriter.write("我已经收到了消息\n");

            bufferedWriter.flush();
            bufferedWriter.close();
            bufferedReader.close();
            serverSocket.close();*/
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
